package com.wtzz.police.base.config;

import com.wtzz.police.base.util.Constant;
import com.wtzz.police.base.util.component.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    private JwtTokenUtil jwtTokenUtil;
    private UserDetailsService userDetailsService;

    public JwtAuthenticationTokenFilter(JwtTokenUtil jwtTokenUtil, UserDetailsService userDetailsService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userDetailsService = userDetailsService;
    }

    /**
     * url参数中带token方式验证，譬如下载超链接时，可将token以参数的方式传入
     *
     * @param request
     * @return
     */
    private boolean urlAuthentication(HttpServletRequest request) {
        if ("GET".equals(request.getMethod()) && StringUtils.isNotEmpty(request.getParameter(Constant.JWT_URL_PARAMETER))) {
            String token = request.getParameter(Constant.JWT_URL_PARAMETER);
            if (StringUtils.isNotEmpty(token)) {
                authenticationToken(request, token);
                return true;
            }
        }
        return false;
    }

    /**
     * headers中存储token
     *
     * @param request
     * @return
     */
    private boolean headerAuthentication(HttpServletRequest request) {
        String authHeader = request.getHeader(Constant.JWT_HEADER);
        if (authHeader != null) {
            final String authToken = authHeader.replace(Constant.JWT_TOKEN_PREFIX, ""); // The part after "Bearer "
            authenticationToken(request, authToken);
            return true;
        }
        return false;
    }

    private void authenticationToken(HttpServletRequest request, String authToken) {
        String username = jwtTokenUtil.getUsernameFromToken(authToken);
        if (logger.isInfoEnabled()) logger.info("checking authentication " + username);
        if (username != null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (jwtTokenUtil.validateToken(authToken)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
                        null,
                        userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);

                if (logger.isInfoEnabled()) logger.info("authenticated primary " + username + ", setting security context");

            }
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        if (headerAuthentication(request) || urlAuthentication(request)) ;
        chain.doFilter(request, response);
    }
}
